import React, { useState } from 'react';
import { Card, Modal, message,Button} from 'antd';
import ProductTable from '../../components/Product/ProductTable';
import ProductForm from '../../components/Product/ProductForm';
import { fetchProducts } from '../../api/product';

const ProductManagement = () => {
  const [formVisible, setFormVisible] = useState(false);
  const [currentProduct, setCurrentProduct] = useState(null);
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState([]);

  // 加载商品数据
  const loadProducts = async () => {
    setLoading(true);
    try {
      // 实际项目中替换为API调用
      // const response = await fetchProducts();
      // setProducts(response.data);
      
      // 模拟加载延迟
      setTimeout(() => {
        setLoading(false);
      }, 800);
    } catch (error) {
      message.error('加载商品数据失败');
      setLoading(false);
    }
  };

  React.useEffect(() => {
    loadProducts();
  }, []);

  const handleCreate = () => {
    setCurrentProduct(null);
    setFormVisible(true);
  };

  const handleEdit = (product) => {
    setCurrentProduct(product);
    setFormVisible(true);
  };

  const handleSubmit = (values) => {
    setLoading(true);
    
    // 模拟API请求
    setTimeout(() => {
      if (currentProduct) {
        message.success('商品更新成功');
      } else {
        message.success('商品创建成功');
      }
      setFormVisible(false);
      setLoading(false);
      loadProducts();
    }, 1000);
  };

  const handleCancel = () => {
    setFormVisible(false);
  };

  return (
    <div className="product-management">
      <Card
        title="商品管理"
        bordered={false}
        extra={
          <Button 
            type="primary" 
            onClick={handleCreate}
            disabled={loading}
          >
            添加商品
          </Button>
        }
      >
        <ProductTable 
          onEdit={handleEdit} 
          onCreate={handleCreate} 
          onRefresh={loadProducts}
          loading={loading}
        />
      </Card>

      <Modal
        title={currentProduct ? "编辑商品" : "创建新商品"}
        open={formVisible}
        onCancel={handleCancel}
        footer={null}
        destroyOnClose
        width={800}
      >
        <ProductForm
          initialValues={currentProduct}
          onFinish={handleSubmit}
          onCancel={handleCancel}
          loading={loading}
        />
      </Modal>
    </div>
  );
};

export default ProductManagement;